package com.online_video.servlet.upload;

import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

@WebServlet("/servlet/upload.do")
@MultipartConfig(location = "D:/img/", fileSizeThreshold = 1024 * 1024 * 5, maxFileSize = 1024 * 1024 * 5 * 5, maxRequestSize = -1)
public class Upload extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        Part part = req.getPart("file");
        String submittedFileName = part.getSubmittedFileName();
        //得到文件的后缀名
        String type = submittedFileName.substring(submittedFileName.lastIndexOf("."));
        //得到文件的名称 由uuid随机得到
        String filename = UUID.randomUUID() + type;
        //设置文件的存放路径
        String path = "D:/img/" + filename;
        part.write(path);
        Gson gson = new Gson();
        String filenameStr = gson.toJson(filename);
        writer.write(filenameStr);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
